import React, { Component } from "react";

import Button from "@component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal, List } from "antd-mobile";
import "./index.scss";
import verCode from "@component/verCode/index";
import { InterfaceG, agreements_url } from "@config/Config";
import { checkIdCardAge, checkTheIdCard } from "@tools/checkIdCard";
import yhTools from "@tools/yh";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";
import { refresh, bs, listener } from "@/component/scroll/index2";
import ListItem from "antd-mobile/lib/list/ListItem";
import CertiBanner from "@/views/viewCommon/certiBanner";

const alert = Modal.alert;

const contract = [
	"《永辉金融隐私政策》",
	"《永辉金融用户协议》",
	"《个人信息使用授权书》",
	"《个人征信授权书》",
	"《个人循环授信借款合同》",
	"《非在校学生身份承诺函》"
];
const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkIdCard = value => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
const phoneSeparated = value => {
	let tel = "";
	if (value) {
		tel =
			value.substring(0, 3) +
			" " +
			value.substring(3, 7) +
			" " +
			value.substring(7, 11);
	}
	return tel;
};
const agreementPageMap = {
	1: "/xhfXy", //此路由不用，换为cdn的隐私协议
	2: "/serviceAgreementAuthorization",
	3: "/personalInformationLicense",
	4: "/personalCreditAuthorization",
	5: "/iframeAgreements",
	6: "/nonStudentCommitmentLetter",
	pay: "/agreementoflianyintong"
};

@verCode()
@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		longitude: state.getAppPlatformsDatas.longitude,
		latitude: state.getAppPlatformsDatas.latitude,
		mobile: state.getAppPlatformsDatas.mobile,
		devicesInfo: state.getAppPlatformsDatas.devicesInfo,
		modal: false
	}),
	dispatch => ({
		_getAppPlatformsDatas: value => dispatch(getAppPlatformsDatas(value))
	})
)
class xhfAddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			idCard: "",
			verifyCode: "",
			channelCode: "YHB",
			//userBankPhone: props.mobile ? phoneSeparated(props.mobile) : "",
			userBankPhone: this.props.pageParams.userBankPhone
				? phoneSeparated(this.props.pageParams.userBankPhone)
				: props.mobile
				? phoneSeparated(props.mobile)
				: "",
			isRead: true,
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			spaceID: "",
			inputDisabled: false,
			isShowStudent: false, //是否显示学生选择
			verifyToken: "",
			isShowBottomButton: false // 显示底部按钮
		};
		this.refInput = React.createRef(null);
		this.xfxButtonRef = React.createRef(null);
		listener(this.onScroll);
	}
	componentWillReceiveProps = nextProps => {
		//props 更新
		const { idCard, userName, inputDisabled, student } = nextProps.pageParams;
		if (nextProps.pageParams.inputDisabled) {
			this.setState({
				//userBankPhone:phoneSeparated(userBankPhone),
				idCard,
				userName,
				inputDisabled,
				isShowStudent: student === "0"
			});
		}
	};
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		let winHeight = document.documentElement.clientHeight;
		let inputElement = this.refInput.current;
		let inputPos = 0;
		if (inputElement) {
			inputPos = inputElement.getBoundingClientRect().top;
			if (inputPos / winHeight < obj.heightper || obj.heightper === 0) {
				return;
			}
		}
		let h = (winHeight * obj.heightper) / 2 + 74;
		if (bs) {
			bs.scrollTo(0, -h);
		}
	};
	componentDidMount = () => {
		if (this.props.getComponetOpenModal) {
			this.props.getComponetOpenModal(this.addZIndex);
		}

		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	};

	//改变zIndex
	minusZIndex = () => {
		if (this.maskElement && this.warpElement) {
			this.maskElement.parentNode.parentNode.style.display = "none";
		}
	};
	addZIndex = () => {
		if (this.maskElement && this.warpElement) {
			this.maskElement.parentNode.parentNode.style.display = "block";
		}
	};
	getMsgCode = () => {
		this.sendMsgCode();
	};
	sendMsgCode = () => {
		const { userName, idCard, userBankPhone, inputDisabled } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		const { sendCodeUrl } = this.props;
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!inputDisabled && !checkIdCard(submitCardRegexp(idCard))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(60); //连连验证码时间
		let objs = {
			url: sendCodeUrl ? sendCodeUrl : InterfaceG.sendVerifyCode,
			params: {
				mobilePhone: submitCardRegexp(userBankPhone),
				scene: "threeElement",
				productNo: "601"
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				// Toast.info("验证码30分钟内验证码有效", 2);
				const { orderNo, verifyToken } = res.data;
				this.setState({
					orderNo,
					verifyToken,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	/**获取位置信息*/
	isHasLocation() {
		const _this = this;
		let longitude = this.props.longitude || "";
		let latitude = this.props.latitude || "";
		if (!longitude || !latitude) {
			//获取经纬度
			window.YHAuthorize.callHandler("Privacy_Loaction", "", res => {
				// if (res.status == "1000") {
				const { data = {} } = res;
				longitude = data.longitude || "";
				latitude = data.latitude || "";
				_this.props._getAppPlatformsDatas({
					longitude,
					latitude,
					devicesInfo: {
						...this.props.devicesInfo,
						longitude,
						latitude
					}
				});
				this.xhfAddBank(longitude, latitude);
				// } else if (res.status == "3001") {
				// 	alert("地理位置授权", "允许永辉金融钱包访问您当前的地理位置信息？", [
				// 		{ text: "取消", onPress: () => {} },
				// 		{ text: "设置", onPress: () => this.openLoction() }
				// 	]);
				// } else {
				// 	Toast.info(res.message, 2);
				// }
			});
		} else {
			this.xhfAddBank(longitude, latitude);
		}
	}
	//去设置允许打开地理位置
	openLoction() {
		yhTools.settingPrivacy();
	}
	xhfAddBank = (longitude, latitude) => {
		const { lnid, applyNo, orderNo, submitUrl } = this.props;
		const {
			verifyCode,
			userBankPhone,
			idCard,
			userName,
			verifyToken
		} = this.state;
		if (this.checkCanSubmit(userBankPhone, verifyCode, idCard, userName)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: submitUrl ? submitUrl : InterfaceG.threeElementAuth,
				params: {
					userName: submitCardRegexp(userName),
					idNo: submitCardRegexp(idCard),
					verifyCode: submitCardRegexp(verifyCode),
					mobilePhone: submitCardRegexp(userBankPhone),
					userDeviceInfo: JSON.stringify(this.props.devicesInfo),
					productNo: "601",
					scene: "threeElement",
					longitude,
					latitude,
					applyNo,
					orderNo,
					verifyToken,
					lnid
				},
				_alertShow: false
			};
			if (verifyToken) {
				this.props.Submit(objs);
			} else {
				Toast.info("请先获取验证码", 2);
			}
			this.setState({
				canSubmit: true
			});
		}
	};
	InputOnChange = (key, value) => {
		//当身份证验证通过后
		if (value && key === "idCard") {
			if (checkTheIdCard(value)) {
				//判断用户是否大于22岁，不含22,小于22岁,选择是否是学生
				if (checkIdCardAge(value)) {
					this.setState({
						isShowStudent: true
					});
				} else {
					this.setState({
						isShowStudent: false
					});
				}
			} else {
				this.setState({
					isShowStudent: false
				});
			}
		}
		if (key == "userName" || key == "idCard") {
			value = value.replace(/^\s*|\s*$/g, ""); //去掉两头空格
		}
		if (key == "idCard") {
			value = value.replace(/x/, "X");
		}
		this.setState({
			[key]: value
		});
	};
	toggleAgree = e => {
		if (e) {
			e.stopPropagation();
		}
		this.setState(prevState => {
			return { isRead: !prevState.isRead };
		});
	};

	checkCanSubmit = (phoneNum, verifyCode, idCard, userName) => {
		if (this.state.inputDisabled) {
			return true;
		} else {
			if (!userName) {
				Toast.info("请输入姓名", 2);
				return false;
			}
			if (!idCard) {
				Toast.info("请输入身份证", 2);
				return false;
			}
			if (!checkIdCard(submitCardRegexp(idCard))) {
				Toast.info("身份证格式不正确", 2);
				return false;
			}
			if (!phoneNum) {
				Toast.info("请填写手机号", 2);
				return false;
			}
			if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
				Toast.info("手机号格式不正确", 2);
				return false;
			}
			if (!this.state.hasSendCode) {
				Toast.info("请获取验证码", 2);
				return false;
			}
			if (!verifyCode.length) {
				Toast.info("请输入验证码");
				return false;
			}
			if (verifyCode.length !== 6) {
				Toast.info("验证码输入错误");
				return false;
			}
			return true;
		}
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return true;
		} else if (res.code === "70010") {
			return false;
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}
	saveBank = () => {
		this.isHasLocation();
	};

	//查看协议
	openContract = type => {
		const { userName, idNo } = this.props.ocrInfo;
		const year = new Date().getFullYear();
		const month = new Date().getMonth() + 1;
		const day = new Date().getDate();
		this.minusZIndex();
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		if (type == 1) {
			//cnd协议
			this.props.pageParams.history.push({
				pathname: "/iframeAgreements",
				state: {
					src: agreements_url + "/privacyAgreement.html",
					title: "永辉金融隐私政策"
				}
			});
		} else if (type == 5) {
			//cnd协议
			this.props.pageParams.history.push({
				pathname: "/iframeAgreements",
				state: {
					src: agreements_url + "/xhfCreditPaymentContract.html",
					title: "个人循环授信借款合同"
				}
			});
		} else {
			//本地协议
			this.props.pageParams.history.push({
				pathname: agreementPageMap[type],
				params: type === "huaTongAccount" ? paramsHuaTong : commonParams
			});
		}
	};
	load = () => {
		refresh();
	};
	onClose = () => {
		this.setState({
			modal: false
		});
	};
	openModal = e => {
		if (e) {
			e.stopPropagation();
		}
		this.setState(
			{
				modal: true
			},
			() => {
				this.maskElement = document.getElementsByClassName("am-modal-mask")[0];
				this.warpElement = document.getElementsByClassName("am-modal-wrap")[0];
			}
		);
	};
	//滚动

	onScroll = () => {
		console.log(111);
		const top =
			this.xfxButtonRef.current &&
			this.xfxButtonRef.current.getBoundingClientRect().top;
		if (top < 0) {
			this.setState({
				isShowBottomButton: true
			});
		} else {
			this.setState({
				isShowBottomButton: false
			});
		}
	};
	resetBtn = () => {
		if (bs) {
			bs.scrollTo(0, 0);
			this.setState({
				isShowBottomButton: false
			});
		}
	};

	render() {
		const {
			userBankPhone,
			// isRead,
			// from,
			hasSendCode,
			idCard,
			userName,
			inputDisabled,
			isShowStudent,
			isShowBottomButton
		} = this.state;
		const { countDown, isClick } = this.props.verCode;
		const { bannerData = {}, submitText } = this.props;
		const { couponAllValue, displayBannerList, inputBgImg } = bannerData;
		return (
			<div className="three-add-bank-pos">
				<div className="three-add-bank-containers">
					<CertiBanner bannerData={bannerData} onLoad={this.load} />
					<div
						style={{
							backgroundImage: `url(${inputBgImg}`
						}}
						className="input-box"
						ref={this.refInput}
					>
						<InputItem
							className="my-input"
							value={userName}
							disabled={inputDisabled}
							placeholder="请输入姓名"
							maxLength={10}
							id="js-fix-bug"
							onChange={this.InputOnChange.bind(this, "userName")}
						>
							姓名
						</InputItem>
						<InputItem
							clear
							maxLength={18}
							type="text"
							id="js-fix-bug"
							placeholder="请输入身份证号码"
							value={idCard}
							disabled={inputDisabled}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "idCard")}
						>
							身份证号码
						</InputItem>
						<InputItem
							clear
							type="phone"
							id="js-fix-bug"
							placeholder="请填写预留手机号"
							value={userBankPhone}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "userBankPhone")}
						>
							预留手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							id="js-fix-bug"
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.getMsgCode}>
								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
						<div className="xhf-btn-box" ref={this.xfxButtonRef}>
							<div style={{ position: "relative" }}>
								<Button
									style={{
										marginTop: "0.2rem"
									}}
									onClick={this.saveBank}
									// disabled={!isRead}
									buttonStyle={{
										height: "1rem",
										lineHeight: "1rem",
										borderRadius: "1.2rem",
										color: "#9b4224",
										background:
											"linear-gradient(180deg, #ffdb66 0%, #f8d151 100%)"
									}}
								>
									{submitText ? submitText : "开通并支付"}
								</Button>
								{couponAllValue && (
									<span className="tip-text">领取{couponAllValue}元券包</span>
								)}
							</div>
							<div className="agree-wrapper">
								<span className="multi-line" onClick={this.openModal}>
									点击按钮，表示您已阅读并同意
									<a className="font-link">《永辉金融相关协议》</a>
								</span>
							</div>
							<Modal
								popup
								visible={this.state.modal}
								onClose={this.onClose}
								animationType="slide-up"
								wrapClassName="contact-slide-up"
							>
								<List className="popup-list">
									{contract.map((item, index) => (
										<List.Item
											key={index}
											onClick={() => this.openContract(index + 1)}
										>
											{item}
										</List.Item>
									))}
									{/* {isShowStudent && idCard && (
										<ListItem
											onClick={() => this.openContract(contract.length + 1)}
										>
											《非在校学生身份承诺函》
										</ListItem>
									)} */}
									<div className="line"></div>
									<ListItem onClick={this.onClose}>取消</ListItem>
								</List>
							</Modal>
						</div>
					</div>
					{displayBannerList && displayBannerList.length > 0
						? displayBannerList.map(item => {
								return (
									<img
										className="three-icon"
										src={item.imgUrl}
										onLoad={this.load}
										key={item.imgUrl}
									/>
								);
						  })
						: ""}
				</div>
				{isShowBottomButton &&
					yhTools.createPortal(
						<div className="three-btn-bottom" key="threePos">
							<Button
								onClick={this.resetBtn}
								buttonStyle={{
									height: "1rem",
									lineHeight: "1rem",
									borderWidth: "0px",
									borderRadius: "1.2rem",
									color: "#9b4224",
									background:
										"linear-gradient(180deg, #ffdb66 0%, #f8d151 100%)"
								}}
							>
								{submitText ? submitText : "开通并支付"}
							</Button>
							{couponAllValue && (
								<span className="tip-text bottom-tip">
									领取{couponAllValue}元券包
								</span>
							)}
						</div>
					)}
			</div>
		);
	}
}
export default xhfAddBank;
